/**
 * 对话编辑页面组件
 * 
 * 功能特性：
 * - 对话信息编辑
 * - 智能体选择
 * - 标签管理
 * - 状态设置
 * - 表单验证
 * - 关联数据展示
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  message,
  Space,
  Switch,
  Tag,
  Divider,
  Alert,
  Row,
  Spin,
  Col,
  Statistic,
  List,
  Avatar,
  Typography,
  Tooltip
} from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { 
  SaveOutlined, 
  ArrowLeftOutlined, 
  ReloadOutlined,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  MessageOutlined,
  ClockCircleOutlined,
  TagOutlined,
  SettingOutlined
} from '@ant-design/icons';
import conversationService, { ConversationStatus } from '@services/conversationService';
import agentService from '@services/agentService';

const { TextArea } = Input;
const { Option } = Select;
const { Text, Paragraph } = Typography;

interface Agent {
  id: string;
  name: string;
  description: string;
  isActive: boolean;
}

interface ConversationFormData {
  title: string;
  description: string;
  agentId: string;
  status: ConversationStatus;
  isActive: boolean;
  tags: string;
}

const ConversationEdit: React.FC = () => {
  const [form] = Form.useForm<ConversationFormData>();
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [agents, setAgents] = useState<Agent[]>([]);
  const [conversationStats, setConversationStats] = useState<any>(null);

  useEffect(() => {
    if (id) {
      loadConversation();
    }
    loadAgents();
  }, [id]);

  const loadConversation = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await conversationService.getConversation(id);
      
      // 设置表单初始值
      form.setFieldsValue({
        title: response.title,
        description: response.description,
        agentId: response.agentId,
        status: response.status,
        isActive: response.isActive,
        tags: response.tags.join(', ')
      });

      // 加载对话统计
      loadConversationStats(id);
    } catch (error) {
      message.error('加载对话信息失败');
      navigate('/conversations');
    } finally {
      setLoading(false);
      setInitialLoading(false);
    }
  };

  const loadAgents = async () => {
    try {
      const response = await agentService.getSimpleAgents(true);
      setAgents(response);
    } catch (error) {
      message.error('加载智能体列表失败');
    }
  };

  const loadConversationStats = async (conversationId: string) => {
    try {
      const stats = await conversationService.getConversationStats(conversationId);
      setConversationStats(stats);
    } catch (error) {
      console.error('加载对话统计失败:', error);
    }
  };

  const handleSubmit = async (values: ConversationFormData) => {
    if (!id) return;
    
    try {
      setSaving(true);
      const updateData = {
        ...values,
        tags: values.tags.split(',').map(tag => tag.trim()).filter(Boolean)
      };
      
      await conversationService.updateConversation(id, updateData);
      message.success('更新对话成功');
      navigate(`/conversations/${id}`);
    } catch (error) {
      message.error('更新对话失败');
    } finally {
      setSaving(false);
    }
  };

  const getStatusColor = (status: ConversationStatus) => {
    const colors = {
      [ConversationStatus.Active]: 'green',
      [ConversationStatus.Closed]: 'red',
      [ConversationStatus.Deleted]: 'gray',
      [ConversationStatus.Archived]: 'gray'
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  const getStatusText = (status: ConversationStatus) => {
    const texts = {
      [ConversationStatus.Active]: '进行中',
      [ConversationStatus.Closed]: '已关闭',
      [ConversationStatus.Deleted]: '已删除',
      [ConversationStatus.Archived]: '已归档'
    };
    return texts[status as keyof typeof texts] || '未知';
  };

  if (initialLoading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <Card
        title="编辑对话"
        extra={
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(`/conversations/${id}`)}>
              返回详情
            </Button>
            <Button icon={<ReloadOutlined />} onClick={loadConversation} loading={loading}>
              重置
            </Button>
          </Space>
        }
      >
        <Alert
          message="编辑对话信息"
          description="修改对话的基本信息、关联智能体、状态设置等。更改智能体可能会影响后续消息的处理逻辑。"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        {/* 统计信息 */}
        {conversationStats && (
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="总消息数"
                  value={conversationStats.messageCount || 0}
                  prefix={<MessageOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="用户消息"
                  value={conversationStats.userMessageCount || 0}
                  prefix={<UserOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="智能体回复"
                  value={conversationStats.assistantMessageCount || 0}
                  prefix={<RobotOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="总Token消耗"
                  value={conversationStats.totalTokens || 0}
                  prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
          </Row>
        )}

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          autoComplete="off"
        >
          {/* 基本信息 */}
          <Card 
            title="基本信息" 
            size="small" 
            style={{ marginBottom: 16 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="title"
                  label="对话标题"
                  rules={[
                    { required: true, message: '请输入对话标题' },
                    { min: 2, max: 100, message: '标题长度在2-100个字符之间' }
                  ]}
                >
                  <Input placeholder="请输入对话标题" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="agentId"
                  label="关联智能体"
                  rules={[{ required: true, message: '请选择关联智能体' }]}
                >
                  <Select placeholder="请选择智能体">
                    {agents.map(agent => (
                      <Option key={agent.id} value={agent.id}>
                        <Space>
                          <span>{agent.name}</span>
                          {agent.isActive ? (
                            <Tag color="green">激活</Tag>
                          ) : (
                            <Tag color="red">禁用</Tag>
                          )}
                        </Space>
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="description"
              label="描述"
              rules={[
                { required: true, message: '请输入描述' },
                { max: 500, message: '描述最多500个字符' }
              ]}
            >
              <TextArea 
                rows={3} 
                placeholder="请输入对话描述"
                maxLength={500}
                showCount
              />
            </Form.Item>

            <Form.Item
              name="tags"
              label="标签"
            >
              <Input placeholder="请输入标签，用逗号分隔" />
            </Form.Item>
          </Card>

          {/* 状态设置 */}
          <Card 
            title="状态设置" 
            size="small" 
            style={{ marginBottom: 16 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="status"
                  label="对话状态"
                  rules={[{ required: true, message: '请选择对话状态' }]}
                >
                  <Select placeholder="请选择对话状态">
                    {Object.values(ConversationStatus).map(status => (
                      <Option key={status} value={status}>
                        <Tag color={getStatusColor(status)}>
                          {getStatusText(status)}
                        </Tag>
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="isActive"
                  label="激活状态"
                  valuePropName="checked"
                >
                  <Switch 
                    checkedChildren="激活" 
                    unCheckedChildren="禁用" 
                  />
                </Form.Item>
              </Col>
            </Row>
          </Card>

          {/* 高级设置 */}
          <Card 
            title="高级设置" 
            size="small" 
            style={{ marginBottom: 24 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            <Alert
              message="注意事项"
              description="更改智能体后，新的消息将由新选择的智能体处理。关闭的对话重新激活后可以继续发送消息。"
              type="warning"
              showIcon
              style={{ marginBottom: 16 }}
            />

            <List
              size="small"
              bordered
              dataSource={[
                {
                  title: '状态变更',
                  description: '不同状态的对话有不同的行为限制',
                  actions: [<SettingOutlined key="setting" />]
                },
                {
                  title: '智能体切换',
                  description: '可以随时更改对话关联的智能体',
                  actions: [<RobotOutlined key="robot" />]
                },
                {
                  title: '标签管理',
                  description: '标签有助于对话的分类和检索',
                  actions: [<TagOutlined key="tag" />]
                }
              ]}
              renderItem={item => (
                <List.Item actions={item.actions}>
                  <List.Item.Meta
                    title={item.title}
                    description={item.description}
                  />
                </List.Item>
              )}
            />
          </Card>

          {/* 操作按钮 */}
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={saving}
                icon={<SaveOutlined />}
              >
                保存更改
              </Button>
              <Button onClick={() => navigate(`/conversations/${id}`)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default ConversationEdit;